package com.open.launcher.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.open.launcher.R;
import com.open.launcher.activity.LauncherApplication;
import com.open.launcher.promote.AuthRunnable;
import com.open.launcher.utils.Consts;
import com.open.launcher.utils.Paths;
import com.open.library.utils.PreferencesUtils;
import com.open.widget.utils.ViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnFocusChange;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by ghq on 2018/4/6.
 */
public class ServiceSettingsFragment extends BaseFragment {
    private static String TAG="ServiceSettingsFragment";
    @BindView(R.id.et_ipaddr)
    EditText etIpAddr;

    Unbinder unbinder;

    @BindView(R.id.et_room_no)
    EditText etRoomNo;
    @BindView(R.id.et_port)
    EditText etPort;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings_service, null);
        unbinder = ButterKnife.bind(this, view);
        etIpAddr.requestFocus();
        //
        String ipAddr = PreferencesUtils.getString(getActivity(), Consts.IP_ADDR_KEY);
        if (!TextUtils.isEmpty(ipAddr)) {
            etIpAddr.setText(ipAddr);
        }
        String ipPort = PreferencesUtils.getString(getActivity(), Consts.IP_ADDR_PORT);
        if (!TextUtils.isEmpty(ipPort)) {
            etPort.setText(ipPort);
        }
        //
        String roomNo = PreferencesUtils.getString(getActivity(), Consts.IP_ROOM_NO_KEY);
        if (!TextUtils.isEmpty(roomNo)){
            etRoomNo.setText(roomNo);
        }
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnFocusChange({R.id.et_ipaddr, R.id.save_btn})
    public void onViewFocusChange(View view, boolean isfocus) {
        ViewUtils.scaleView(view, isfocus);
    }

    @OnClick({R.id.save_btn})
    public void onViewClick(View view) {
        final String ipAddr = etIpAddr.getText().toString().trim();
        String roomNo = etRoomNo.getText().toString().trim();
        String port = etPort.getText().toString().trim();
        if (TextUtils.isEmpty(ipAddr)) {
            showToast(R.string.empty_ipaddr_tip);
            return;
        }
        if (TextUtils.isEmpty(roomNo)) {
            showToast(R.string.empty_roomno_tip);
            return;
        }
        if (TextUtils.isEmpty(port)) {
            showToast("房间号不能为空");
            return;
        }
        // 保存房间号
        PreferencesUtils.putString(getActivity(), Consts.IP_ROOM_NO_KEY, roomNo);
        PreferencesUtils.putString(getActivity(), Consts.IP_ADDR_PORT, port);
        // TODO: 点击确认 测试后台链接
        if (!TextUtils.isEmpty(ipAddr)) {
            // 保存IP地址.
            PreferencesUtils.putString(getActivity(), Consts.IP_ADDR_KEY, ipAddr);
            // 發送IP地址測試.
            Request request=new Request.Builder()
                    .url("http://" + ipAddr).build();
            Call call = ((LauncherApplication) getActivity().getApplication()).getOkHttp().getOkHttpClient().newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "服务器地址请求失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "服务器地址请求成功", Toast.LENGTH_SHORT).show();
                            Consts.ROOT_ADDR = "http://" + ipAddr;
//                            "http://"+PreferencesUtils.getString(this, Consts.IP_ADDR_KEY)="http://"+ipaddr;
//                            "http://"+PreferencesUtils.getString(this, Consts.IP_ADDR_KEY)IP=ipaddr;
                            Consts.ROOT_ADDRIP = ipAddr;

                        }
                    });
                }
            });
//            ((LauncherApplication) getActivity().getApplication()).getOkHttp().get().url("http://" + etIpAddr.getText().toString())
//                    .enqueue(new RawResponseHandler() {
//                        @Override
//                        public void onFailure(int statusCode, String error_msg) {
//                            Toast.makeText(getActivity(), "服务器地址请求失败", Toast.LENGTH_SHORT).show();
//                        }
//
//                        @Override
//                        public void onSuccess(int statusCode, String response) {
//                            Toast.makeText(getActivity(), "服务器地址请求成功", Toast.LENGTH_SHORT).show();
//                            Consts.ROOT_ADDR = ipaddr;
//                        }
//                    });
        }
        // 发送一次websocket. okGoUtil.params("room_number",username);
//        okGoUtil.params("mac",password);
        OkHttpUtils.post().url("http://"+ipAddr+Paths.SETTING_REGISRE).
                addParams("room_number",roomNo)
                .addParams("mac", AuthRunnable.getLocalEthernetMacAddress())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i(TAG, "onError: " +e.toString());
                Toast.makeText(getActivity(), "网络异常", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i(TAG, "onError: " +response.toString());
//                HeartBean bean = JSON.parseObject(response,HeartBean.class);
//                switch (bean.getCode()){
//                    case 0:
//                        Toast.makeText(getActivity(), bean.getMessage(), Toast.LENGTH_SHORT).show();
//                        break;
//                    case 1:
//                        Toast.makeText(getActivity(), bean.getMessage(), Toast.LENGTH_SHORT).show();
//                        break;
//                    case 2:
//                        Toast.makeText(getActivity(), bean.getMessage(), Toast.LENGTH_SHORT).show();
//                        break;
//                }

            }
        });
//        getActivity().startService(new Intent(getActivity(), WebSocketService.class));
    }

}
